package com.wenbai.servicelightluxurystickers.interceptor;

import com.wenbai.servicelightluxurystickers.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头获取token
        String token = request.getHeader("Authorization");

        if (token == null || token.isEmpty()) {
            // 没有token，拦截
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            response.getWriter().write("无token，请重新登录！");
            return false;
        }

        boolean isValid = TokenUtils.verify(token);

        if (!isValid) {
            // token无效，拦截
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            response.getWriter().write("token无效或过期，请重新登录");
            return false;
        }

        // token验证通过，放行
        return true;
    }
}
